<template>
  <div class="login-wrapper">
    <MHeader :title="title"/>
    <img :src="logo" class="logo" alt="logo"/>
    <div class="login-body">
      <van-form @submit="onSubmit">
        <van-field
            v-model="form.username"
            :rules="rules.username"
            clearable
            name="username"
            label="手机号码"
            placeholder="手机号码"
        />
        <van-field
            v-model="form.password"
            :rules="rules.password"
            clearable
            type="password"
            name="password"
            label="密码"
            placeholder="密码"

        />
        <van-field
            center
            clearable
            label="验证码"
            placeholder="输入验证码"
            v-model="form.verify"
            :rules="rules.verify"
        >
          <template #button>
            <ImageVerify ref="imageVerifyRef"/>
          </template>
        </van-field>
        <div style="margin: 16px;">
          <div v-if="type===IType.LOGIN" class="link-register" @click="changeType(IType.REGISTER)">立即注册</div>
          <div v-if="type===IType.REGISTER" class="link-login" @click="changeType(IType.LOGIN)">已有登录账号</div>
          <van-button
              :loading="isLoading"
              round
              block
              color="#1baeae"
              native-type="submit"
              :loading-text="`${title}中...`"
          >
            {{ title }}
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
<script setup lang="ts">
import {computed, ref} from "vue";
import {useRouter, useRoute} from "vue-router";
import MHeader from "@/components/MHeader/index.vue";
import logo from '@/assets/images/logo.png';
import ImageVerify from "@/components/ImageVerify/index.vue";
import {showSuccessToast, showToast} from "vant";
import loginAPI from "@/api/user/loginAPI";
import {md5} from "js-md5";
import registerAPI from "@/api/user/registerAPI";
import {SUCCESS_CODE} from "@/constants";
import useToken from "@/hooks/useToken";

enum IType {
  LOGIN = 'login',
  REGISTER = 'register',
}

defineOptions({
  name: 'Login'
})

const type = ref<IType>(IType.LOGIN);
const {token} = useToken();
const title = computed(() => {
  return type.value === IType.LOGIN ? '登录' : '注册'
})

const imageVerifyRef = ref<typeof ImageVerify | null>(null)
const isLoading = ref(false);
const form = ref({
  username: '',
  password: '',
  verify: ''
})

const rules = {
  username: [{required: true, message: '请填写手机号码'}],
  password: [{required: true, message: '请填写密码'}],
  verify: [{required: true, message: '请填写验证码'},],
}

const router = useRouter();
const route = useRoute();

const changeType = (value: IType) => {
  type.value = value;
  form.value = {
    username: '',
    password: '',
    verify: '',
  };
  imageVerifyRef.value?.handleDraw();
}

const onSubmit = async () => {
  if (form.value.verify.toLowerCase() !== imageVerifyRef.value?.state.imgCode.toLowerCase()) {
    showToast('验证码错误')
    return;
  }
  if (isLoading.value) {
    return
  }
  try {
    isLoading.value = true;
    let response;
    if (type.value === IType.LOGIN) {
       response = await loginAPI({
        loginName: form.value.username,
        passwordMd5: md5(form.value.password),
      })
      if (response.code === SUCCESS_CODE) {
        showSuccessToast('登录成功');
       token.value =  response.data;
        const redirect = (route.query?.redirect || '') as string;
        if (redirect) {
          router.replace({path: redirect});
        } else {
          router.replace({path: '/home'});
        }
      }
    } else if (type.value === IType.REGISTER) {
      response = await registerAPI({
        loginName: form.value.username,
        password: form.value.password,
      })
      if (response.code === SUCCESS_CODE) {
        showSuccessToast('注册成功，请登录');
        changeType(IType.LOGIN);
      }
    }
  } catch (e: any) {
    showToast(e.message);
  } finally {
    isLoading.value = false;
    imageVerifyRef.value?.handleDraw();
  }
}
</script>
<style scoped lang="less">
.login-wrapper {
  .logo {
    width: 120px;
    height: 120px;
    display: block;
    margin: 80px auto 20px;
  }

  .link-register,
  .link-login {
    font-size: 14px;
    margin-bottom: 20px;
    color: #1989fa;
    display: inline-block;
  }
}
</style>